package com.cskaoyan.market.service.admin.impl;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.service.admin.MarketGoodsService;
import com.cskaoyan.market.vo.admin.CatAndBrandVo;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MarketGoodsServiceImpl implements MarketGoodsService {
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketCategoryMapper categoryMapper;
    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketGoodsAttributeMapper attributeMapper;


    @Override
    public List<MarketGoods> list(Integer page, Integer limit, String goodsSn, String sort, String order, String goodsId, String name) {

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        // 创建一个基本条件
        MarketGoodsExample.Criteria criteria = goodsExample.or().andDeletedEqualTo(false);
        // goodsSn goodsId name 条件
        if (!StringUtils.isEmpty(goodsSn)) {
            criteria.andNameLike("%" + goodsSn + "%");
        }
        if (!StringUtils.isEmpty(goodsId)) {
            criteria.andIdEqualTo(Integer.valueOf(goodsId));
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        // page limit 分页使用
        // sort order 排序使用
        goodsExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);
        List<MarketGoods> marketGoodsList = goodsMapper.selectByExample(goodsExample);
        return marketGoodsList;
    }

    @Override
    public Map<String, Object> catAndBrand() {
        // 查询category
        List<MarketCategory> marketCategories = categoryMapper.selectByExampleSelective(new MarketCategoryExample(),
                MarketCategory.Column.id, MarketCategory.Column.name, MarketCategory.Column.pid);
        // 查询品牌
        List<MarketBrand> marketBrands = brandMapper.selectByExampleSelective(new MarketBrandExample(), MarketBrand.Column.id, MarketBrand.Column.name);

        // 拼接
        Map<Integer, List<MarketCategory>> categoriesGroupByPid = new HashMap<>();
        for (MarketCategory marketCategory : marketCategories) {
            Integer pid = marketCategory.getPid();
            List<MarketCategory> levelCategories = categoriesGroupByPid.get(pid);
            if (levelCategories == null) {
                levelCategories = new ArrayList<>();
                categoriesGroupByPid.put(pid, levelCategories);
            }
            levelCategories.add(marketCategory);
        }
        List<MarketCategory> l1Categories = categoriesGroupByPid.get(0);
        List<CatAndBrandVo> categoriesVOS = new ArrayList<>();
        for (MarketCategory l1Category : l1Categories) {
            CatAndBrandVo l1cavo = new CatAndBrandVo();
            l1cavo.setValue(l1Category.getId());
            l1cavo.setLabel(l1Category.getName());
            //取出其二级类目
            List<MarketCategory> l2categories = categoriesGroupByPid.get(l1Category.getId());
            List<CatAndBrandVo> children = new ArrayList<>();
            // TODO 空指针异常
            for (MarketCategory l2category : l2categories) {
                CatAndBrandVo l2cavo = new CatAndBrandVo();
                l2cavo.setValue(l2category.getId());
                l2cavo.setLabel(l2category.getName());
                children.add(l2cavo);
            }
            l1cavo.setChildren(children);
            categoriesVOS.add(l1cavo);
        }
        List<CatAndBrandVo> brandVos = new ArrayList<>();
        for (MarketBrand marketBrand : marketBrands) {
            brandVos.add(new CatAndBrandVo(marketBrand.getName(), marketBrand.getId(), null));
        }
        //将上述的两个list封装成为一个map，返回即可
        Map<String, Object> catAndBrandsVOS = new HashMap<>();
        catAndBrandsVOS.put("categoryList", categoriesVOS);
        catAndBrandsVOS.put("brandList", brandVos);
        return catAndBrandsVOS;
    }

    /**
     * @MethodName addGoods
     * @Description 对
     * @param: goods    商品对象
     * @param: specifications   规格list
     * @param: attributes   产品list
     * @param: products     属性list
     * @return: int
     * @Author MZ
     * @Date 20:22 2023/5/9
     **/
    @Override
    @Transactional
    public int addGoods(MarketGoods goods, List<MarketGoodsSpecification> specifications, List<MarketGoodsAttribute> attributes, List<MarketGoodsProduct> products) {
        // 插入goods信息
        goods.setAddTime(LocalDateTime.now());
        goods.setUpdateTime(LocalDateTime.now());
        // 获取一个最低价格作为零售价格
        BigDecimal retailPrice = products.get(0).getPrice();
        for (int i = 1; i < products.size(); i++) {
            if (retailPrice.compareTo(products.get(i).getPrice()) == 1) {
                retailPrice = products.get(i).getPrice();
            }
        }
        goods.setRetailPrice(retailPrice);
        goods.setDeleted(false);

        goodsMapper.insert(goods);
        // 获取goodsId
        Integer id = goods.getId();
        // 分别插入另外三张表数据
        // specifications
        for (MarketGoodsSpecification sp : specifications) {
            sp.setGoodsId(id);
            sp.setDeleted(false);
            sp.setAddTime(LocalDateTime.now());
            sp.setUpdateTime(LocalDateTime.now());
            specificationMapper.insert(sp);
        }
        // attributes
        for (MarketGoodsAttribute ab : attributes) {
            ab.setGoodsId(id);
            ab.setDeleted(false);
            ab.setAddTime(LocalDateTime.now());
            ab.setUpdateTime(LocalDateTime.now());
            attributeMapper.insert(ab);
        }
        // products
        for (MarketGoodsProduct pd : products) {
            pd.setGoodsId(id);
            pd.setDeleted(false);
            pd.setAddTime(LocalDateTime.now());
            pd.setUpdateTime(LocalDateTime.now());
            productMapper.insert(pd);
        }
        return 1;
    }
}
